package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.AudioApi;

import com.tanhua.dubbo.server.pojo.Audio;

import com.tanhua.server.vo.AudioUploadResult;
import com.tanhua.server.vo.AudioVo;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Service
public class AudioService {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AudioUploadService audioUploadService;

    @Reference(version = "1.0.0")
    private AudioApi audioApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //上传语音
    public boolean saveAudio(MultipartFile soundFile) {
        //获取user对象,token

        User user = UserThreadLocal.get();
        //创建语音对象
        Audio sound = new Audio();
        //设置redis的key
        String redisKey = "Voice_Send_" + user.getId();
        //设置value
        String value = this.redisTemplate.opsForValue().get(redisKey);

//判断值为空
        if (StringUtils.isEmpty(value)) {
            //设置一天的时间的remainingTimes剩余次数为十
            redisTemplate.opsForValue().set(redisKey,


                    "10", Duration.ofDays(1));
            //redisTemplate.expire(redisKey,1, TimeUnit.DAYS);
        }
        //判断剩余次数是否为小于0
        if (Integer.valueOf(redisTemplate.opsForValue().get(redisKey)) <= 0) {
            return false;
        }

        sound.setUserId(user.getId());
        try {
            //上传声音文件
            AudioUploadResult soundUploadResult = this.audioUploadService.upload(soundFile);
            sound.setAudioUrl(soundUploadResult.getName());
            if (redisTemplate.hasKey(redisKey)) {
                this.redisTemplate.opsForValue().decrement(redisKey);
            }

            return this.audioApi.saveSound(sound);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    //创建soundvo对象
    public AudioVo queryAudio() {
        //创建user对象
        User user = UserThreadLocal.get();
        //创建redis的ke与value
        String redisKey = "Voice_Get_" + user.getId();
        String value = this.redisTemplate.opsForValue().get(redisKey);
        //value为空则添加剩余次数为十;有一天的使用期限
        if (StringUtils.isEmpty(value)) {
            redisTemplate.opsForValue().set(redisKey, "10", Duration.ofDays(1));
            //redisTemplate.expire(redisKey,1, TimeUnit.DAYS);
        }
        //查询所有的语音文件存入集合
        List<Audio> list = audioApi.querySoundList(user.getId());
        //创建一个long的list集合
        List<Long> idList = new ArrayList<>();
        //循环将sound对象的userId存入idlist集合中
        for (Audio sound : list) {
            idList.add(sound.getUserId());
        }
//
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", idList);
        //获取userinfo集合
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        List<AudioVo> newList = new ArrayList<>();


        for (Audio sound : list) {
            for (UserInfo userInfo : userInfos) {
                if (sound.getUserId() == userInfo.getUserId().longValue()) {
                    AudioVo soundVo = new AudioVo();
                    soundVo.setUserId(sound.getUserId());
                    soundVo.setNickname(userInfo.getNickName());
                    soundVo.setAvatar(userInfo.getLogo());
                    soundVo.setAge(userInfo.getAge());
                    soundVo.setSoundUrl(sound.getAudioUrl());
                    soundVo.setRemainingTimes(Integer.valueOf(redisTemplate.opsForValue().get(redisKey)));
                    newList.add(soundVo);
                    break;
                }
            }
        }

        if (redisTemplate.hasKey(redisKey)) {
            this.redisTemplate.opsForValue().decrement(redisKey);
        }


        return newList.get(RandomSound(list,user));

    }

    /**
     * 随机生成语音，保证不重复
     *
     * @param newList
     */
    private int RandomSound(List<Audio> newList,User user) {
        int index=RandomUtils.nextInt(0, newList.size() - 1);
        Audio sound = newList.get(index);
        String key="Voice_Random_"+sound.getId()+user.getId();
        String value=redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(value)){
            RandomSound(newList,user);
        }
        redisTemplate.opsForValue().set(key,"1");
        return  index;

    }
}
